package app.controllers;

import app.models.Fornecedor;
import app.models.enums.EstadosBrasileiros;
import app.services.FornecedorService;
import app.services.LogService;
import app.util.Constants;
import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.Validator;

@Resource
public class FornecedorController extends Controller{

    private Result result;
    private FornecedorService service;
    private Validator validator;
    private LogService logService;
	
    public FornecedorController(Result result, FornecedorService service, Validator validator, LogService logService) {
        this.result = result;
        this.service = service;
        this.validator = validator;
        this.logService = logService;
    }
    
    @Get("/fornecedor")
    public void index() {
    	result.include("fornecedores", service.findAll());
    	result.include("ultimosFornecedores", service.findLastFornecedores());
    }
    
	@Get("/fornecedor/new")
	public void form() {
		result.include("estadosBrasileiros", EstadosBrasileiros.values());
	}
	
	@Post("/fornecedor/save")
	public void save(Fornecedor fornecedor) {
		
		validator.validate(fornecedor);
		validator.validate(fornecedor.getEndereco());
		
		validator.onErrorForwardTo(this).form();
		
		service.create(fornecedor);
		
		logService.createLog(Constants.NEW_FORNECEDOR + fornecedor.getId());
		
		result.forwardTo(this).index();
	}
	
	@Get("/fornecedor/{id}/edit")
	public void edit(Long id) {
		result.include("fornecedor", service.find(id));
	}
	
	@Get("/fornecedor/{id}/show")
	public void show(Long id) {
		result.include("fornecedor", service.find(id));
	}
	
	@Post("/fornecedor/update")
	public void update(Fornecedor fornecedor) {
		
		validator.validate(fornecedor);
		validator.validate(fornecedor.getEndereco());
		
		validator.onErrorForwardTo(this).edit(fornecedor.getId());
		
		service.update(fornecedor);
		
		logService.createLog(Constants.UPDATE_FORNECEDOR + fornecedor.getId());
		
		this.result.forwardTo(this).index();
	}
    
}
